/// <reference path="../Scripts/jquery-1.7.1.min.js" />
/// <reference path="../Scripts/knockout-2.1.0.js" />


function ApplicationRolesViewModel() {
    var self = this;
    // put a property loop here
    self.ApplicationRoleId = ko.observable();
    self.RoleName = ko.observable();
    self.TS = ko.observable();
    self.CreatedBy = ko.observable();
    self.CreatedDt = ko.observable();
    self.ModifiedBy = ko.observable();
    self.ModifiedDt = ko.observable();
    self.ApplicationID = ko.observable();
    self.Action = ko.observable();
    self.Caller = ko.observable();
    self.Role = ko.observable();
    self.PageSize = ko.observable();
    self.PageNumber = ko.observable();
    self.SortColumn = ko.observable();
    self.SortType = ko.observable();
    self.TotalRows = ko.observable();
    self.Application = ko.observable();

    self.selectedVal = ko.observableArray([]);
    //self.ApplicationRoles = ko.observable();
    self.addappid = ko.observableArray();
    self.AddingRole = ko.observable();
    self.LoadingRoles = ko.observable();
    self.EditingRole = ko.observable();

    self.ApplicationRolesList = ko.observableArray([]);
    self.setApplicationRoles = function (
			ApplicationRoleId, RoleName, TS, CreatedBy, CreatedDt, ModifiedBy, ModifiedDt, ApplicationID, _Action, _Caller, _Role, _PageNumber, _PageSize, _SortColumn, _SortType, _TotalRows

	) {

        ApplicationRoleId = _ApplicationRoleId;
        RoleName = _RoleName;
        TS = _TS;
        CreatedBy = _CreatedBy;
        CreatedDt = _CreatedDt;
        ModifiedBy = _ModifiedBy;
        ModifiedDt = _ModifiedDt;
        ApplicationID = _ApplicationID;
        Action = _Action;
        Caller = _Caller;
        Role = _Role;
        PageSize = _PageSize
        PageNumber = _PageNumber;
        SortColumn = _SortColumn;
        SortType = _SortType;
        TotalRows = _TotalRows;

    }; //  End of set procedure 

    self.availableApplication = function () {
        var self = this;
        self.Action = "GetAll";
        self.Caller = "trooks";

        jQuery.ajax({
            url: "./api/ApplicationApi/",
            type: 'get',
            data: { Action: self.Action, Caller: self.Caller, Role: self.Role, PageNumber: self.PageNumber, PageSize: self.PageSize, SortColumn: self.SortColumn, SortType: self.SortType },
        }).done(function (data) {          
            self.addappid.removeAll();
            $.each(data, function (key, val) {                
                self.addappid.push(new appItem(val.ApplicationID, val.ApplicationName));
            })
        });
    };

    function appItem(id, name) {
        this.ApplicationID = ko.observable(id);
        this.ApplicationName = ko.observable(name);

    }

    self.AddRoles = function (appVal2) {
        self.availableApplication(appVal2);
        self.AddingRole(appVal2);
    };

    //Add Roles
    self.AddRole = function () {
        var self = this;
        self.Action = "Add";
        self.Caller = "trooks";
        self.Role = "user";

        $(".form").validate({ rules: { txtRoleName: { required: true } } });
        if (!$(".form").valid()) {
            return;
        }
        jQuery.ajax({
            url: "./api/ApplicationRolesapi/",
            data: ko.toJSON({ RoleName: self.RoleName, Action: self.Action, Caller: self.Caller, ApplicationID: self.selectedVal().ApplicationID }),
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                $('#myModaladd').modal('hide');
                self.GetApplicationRolesByParameter();
                //alert(result);
            },
            error: function (xhr, ajaxOptions, thrownError) {
            $('#error-dis').text(thrownError);
            $('#register-error').css({ 'display': 'block' });
            $('#SearchFilter-home').css({ 'display': 'none' });
            $('#myModaladd').modal('hide');
            $(document).scrollTop(0);
        }
        });
        $(".form")[0].reset();
    }; 
    
    self.LoadRoles = function (appVal) {       
        self.LoadingRoles(appVal);
    };
    //Delete Roles
    self.DeleteRole = function (appval) {
        //var self = this;
        //alert("Delete Action " + self.ApplicationRoleId);
        self.Action = "Remove";
        self.Caller = "trooks";
        jQuery.ajax({
            url: "./api/ApplicationRolesapi/",
            data: ko.toJSON({ Action: self.Action, Caller: self.Caller, ApplicationRoleId: appval.ApplicationRoleId, TS: appval.TS }),
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
        success: function (result) {
            $('#myModel').modal('hide');
            self.GetApplicationRolesByParameter();
            //alert(result);
        },
            error: function (xhr, ajaxOptions, thrownError) {
            $('#error-dis').text(thrownError);
            $('#register-error').css({ 'display': 'block' });
            $('#SearchFilter-home').css({ 'display': 'none' });               
            $(document).scrollTop(0);
            $('#myModel').modal('hide');
            }
        });
    };
    //Edit Roles
    self.EditRole = function (appVal) {
        self.EditingRole(appVal);
    };

    self.UpdateRole = function (appval) {
        self.Action = "Update";
        self.Caller = "trooks";
        self.Role = "user";

        $(".form1").validate({ rules: { txtRoleName: { required: true } } });
        if (!$(".form1").valid()) {
            return;
        }

        jQuery.ajax({
            url: "./api/ApplicationRolesapi/",
            data: ko.toJSON({ RoleName: appval.RoleName, Action: self.Action, Caller: self.Caller, ApplicationID: appval.ApplicationID, ApplicationRoleId: appval.ApplicationRoleId, TS: appval.TS, CreatedBy: appval.CreatedBy, CreatedDt: appval.CreatedDt, ModifiedBy: appval.ModifiedBy, ModifiedDt: appval.ModifiedDt }),
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                $('#myModalEdit').modal('hide');
                self.GetApplicationRolesByParameter();
            },
            error: function (xhr, ajaxOptions, thrownError) {
            $('#error-dis').text(thrownError);
            $('#register-error').css({ 'display': 'block' });
            $('#SearchFilter-home').css({ 'display': 'none' });
            $('#myModalEdit').modal('hide');
            $(document).scrollTop(0);
        }
    
        });
    }; //End of add procedure
    //Sort Roles
    ko.bindingHandlers.sort = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            var asc = false;
            element.style.cursor = 'pointer';

            element.onclick = function () {
                var value = valueAccessor();
                var prop = value.prop;
                var data = value.arr;

                asc = !asc;
                if (asc) {
                    self.ApplicationRolesList.sort(function (left, right) {
                        return left[prop] == right[prop] ? 0 : left[prop] < right[prop] ? -1 : 1;
                    });
                } else {
                    self.ApplicationRolesList.sort(function (left, right) {
                        return left[prop] == right[prop] ? 0 : left[prop] > right[prop] ? -1 : 1;
                    });
                }
            }
        }
    };

    //loading model popup
    ko.bindingHandlers['modal'] = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var allBindings = allBindingsAccessor();
            var $element = $(element);
            $element.addClass('hide modal');

            if (allBindings.modalOptions) {
                if (allBindings.modalOptions.beforeClose) {
                    $element.on('hide', function () {
                        return allBindings.modalOptions.beforeClose();
                    });
                }
            }

            return ko.bindingHandlers['with'].init.apply(this, arguments);
        },
        update: function (element, valueAccessor) {
            var value = ko.utils.unwrapObservable(valueAccessor());

            var returnValue = ko.bindingHandlers['with'].update.apply(this, arguments);

            if (value) {
                $(element).modal('show');
            } else {
                $(element).modal('hide');
            }

            return returnValue;
        }
    };

    //filter

    self.ApplicationRolesList = ko.observableArray([]);
    self.filter = ko.observable("");

    self.filteredRoles = ko.computed(function () {
        var filterText = self.filter().toLowerCase();
        return ko.utils.arrayFilter(self.ApplicationRolesList(), function (item) {
            return filterText.length < 1 || item.RoleName == filterText || item.RoleName.toLowerCase().indexOf(filterText) != -1
        });

    }, self);
    self.GetApplicationRolesByParameter = function () {

        this.Action = "GetAll";
        this.Caller = "trooks";
        this.Role = "user";
        this.PageNumber = 1;
        this.PageSize = 10;
        this.SortColumn = "ApplicationRolesID";
        this.SortType = "asc";
        
        jQuery.ajax({
            url: "./api/ApplicationRolesapi/",
            data: { Action: self.Action, Caller: self.Caller, Role: self.Role, PageNumber: self.PageNumber, PageSize: self.PageSize, SortColumn: self.SortColumn, SortType: self.SortType },
            type: 'get',

            success: function (result) {
                self.ApplicationRolesList.removeAll();
            $.each(result, function (key, val) {
                self.ApplicationRolesList.push(
                    val
                )
            })
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#error-dis').text(thrownError);
            $('#register-error').css({ 'display': 'block' });
            $('#SearchFilter-home').css({ 'display': 'none' });                
            $(document).scrollTop(0);
        }
       
        });
        if (loginUserRole.indexOf('user') > -1) {
            $('.add-btn').attr('disabled', 'disabled');
        }
    };


}; //End of view model


